package sjsu.android;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import dbAdapter.DailyInfoDBAdapter1;
import dbAdapter.ProfileDBAdapter;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ExpandableListActivity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Exercise extends ExpandableListActivity{
	public static ProgressBar pb;
	static DailyInfoDBAdapter1 db;
	private ProfileDBAdapter dbp;
	public static TextView textViewCal;
	public TextView displayDate;
	boolean buttonclicked = false;
	 String [] exerciseList = null ;
	public SimpleExpandableListAdapter expListAdapter = null;
	static final String colors[] = {
		  "My Activity",
			};
	static  String [][] shades1;
	private static final int advancedId = Menu.FIRST;
    private static final int addToProfileId = Menu.FIRST + 1;
    private static final int fitnessId = Menu.FIRST + 2;
    public static int caloriesBurnt ;
    Button adv_cat;
    static int id = 0;
    public ChangeDate date1 = null;
    Calendar c = Calendar.getInstance();
    public int month = c.get(Calendar.MONTH) +1;
    public int year = c.get(Calendar.YEAR);
    public int day = c.get(Calendar.DAY_OF_MONTH);
    Exercise exerciseObj = null;
    Date currentDate = null;
    
    private static class EfficientAdapter extends BaseAdapter {
	private LayoutInflater mInflater;
	int monthE;
	 int dayE;
	 int yearE;
	 Exercise context1;
	 public EfficientAdapter(Context context) {
		 
		 context1 = (Exercise) context;
		 	 mInflater = LayoutInflater.from(context);
		 	  
	 }
	 public int getCount() {
	 return country.length;
	 }
	 
	 public Object getItem(int position) {
	 return position;
	 }
	 public long getItemId(int position) {
	 return position;
	 }
	 
	 public View getView(int position, View convertView, ViewGroup parent) {
		// final Exercise exercise = new Exercise();
	 final ViewHolder holder;
	 
	 if (convertView == null) {
	 convertView = mInflater.inflate(R.layout.excercise, null);
	 holder = new ViewHolder();

	 holder.text1 = (TextView) convertView
	 .findViewById(R.id.TextView02);
	 holder.buttonLight = (Button) convertView
	 .findViewById(R.id.btnLight);
	 holder.buttonMod = (Button) convertView
	 .findViewById(R.id.btnMod);
	 holder.buttonVigorous = (Button) convertView
	 .findViewById(R.id.btnVirgious);
	 convertView.setTag(holder);
	 
	 } else {
	 holder = (ViewHolder) convertView.getTag();
	 }
	 holder.text1.setText(country[position]);
	 holder.buttonLight.setText(light);
	 holder.buttonMod.setText(mod);
	 holder.buttonVigorous.setText(vigorous);
	 holder.buttonLight.setTag(position);
	 holder.buttonLight.setBackgroundResource(R.drawable.zen_button_red);
	 holder.buttonMod.setBackgroundResource(R.drawable.button_yellow);
	 holder.buttonVigorous.setBackgroundResource(R.drawable.button_red);
	 holder.buttonLight.setOnClickListener(new OnClickListener(){
		
     public void onClick(View v) {
   	String t = ""+ v.getTag();
   	  int tag = new Integer(t);
   	  int calBurned = 200;
   	monthE = context1.month;
	  dayE = context1.day;
	  yearE = context1.year;
 //  	 holder.buttonLight.setBackgroundResource(R.color.yellow3);
   	holder.buttonLight.setBackgroundResource(R.drawable.zen_button_red);
   	  context1.insertIntoDB(calBurned);
   	updateProgressBar(monthE,dayE,yearE);
   	  holder.buttonLight.setClickable(false);
   	  holder.buttonMod.setClickable(false);
   	  holder.buttonMod.setVisibility(0);
   	  holder.buttonVigorous.setClickable(false);
   	  holder.buttonVigorous.setVisibility(0);
   	context1.simpleExpandable();
    context1.updateWhatIBurnt();
   	  
   }
});
	 holder.buttonMod.setTag(position);
	 holder.buttonMod.setOnClickListener(new OnClickListener(){
         public void onClick(View v) {
       	String tMod = ""+ v.getTag();
       	  int tagMod = new Integer(tMod);
       	  int calBurned = 400;
       	monthE = context1.month;
	 	  dayE = context1.day;
	 	  yearE = context1.year;
      // 	  holder.buttonMod.setBackgroundResource(R.color.greenyellow);
       	holder.buttonMod.setBackgroundResource(R.drawable.button_yellow);
       	  context1.insertIntoDB(calBurned);
       	  updateProgressBar(monthE,dayE,yearE);
       	  holder.buttonLight.setClickable(false);
       	  holder.buttonMod.setClickable(false);
       	  holder.buttonVigorous.setClickable(false);
       	context1.simpleExpandable();
        context1.updateWhatIBurnt();
       }
   });
	 holder.buttonVigorous.setTag(position);
	 holder.buttonVigorous.setOnClickListener(new OnClickListener(){
         public void onClick(View v) {
       	String tVigorous = ""+ v.getTag();
       	  int tagVigorous = new Integer(tVigorous);
  //    	holder.buttonVigorous.setBackgroundResource(R.color.orangered);
      	 holder.buttonVigorous.setBackgroundResource(R.drawable.button_red);
       	  int calBurned = 750;
       	monthE = context1.month;
	 	  dayE = context1.day;
	 	  yearE = context1.year;
       	 context1.insertIntoDB(calBurned);
       	 updateProgressBar(monthE,dayE,yearE);
       	  holder.buttonLight.setClickable(false);
       	  holder.buttonMod.setClickable(false);
       	  holder.buttonVigorous.setClickable(false);
       	context1.simpleExpandable();
        context1.updateWhatIBurnt();
       }
   });
	 return convertView;
	 }
	 
	 public  EfficientAdapter getObject(){
		return this;
	 }
	 static class ViewHolder {
	 TextView text;
	 TextView text1;
	 TextView text2;
	 TextView text3;
	 Button buttonLight;
	 Button buttonMod;
	 Button buttonVigorous;
	 
	 }
	 }
	 
	 @Override
	 public void onCreate(Bundle savedInstanceState) {
		 db = new DailyInfoDBAdapter1(this);
		 simpleExpandable();
	 super.onCreate(savedInstanceState);
	
	 Date date = convertStringToDate(day, month, year);
	 try{
		 	dbp = new ProfileDBAdapter(this);
		 	db.open();
		  id = dbp.getId();
		 
		  System.out.println("id:"+ id);
		  db.close();
		 }catch (Exception ex){
			 System.out.println("Exception in Custom_ProfileDB");
		 }
		 
		
	 setContentView(R.layout.excercisemain);
	 updateWhatIBurnt();
	 exerciseObj = this;
	 pb = (ProgressBar) findViewById(R.id.progressbar_Horizontal);
	 ListView l1 = (ListView) findViewById(R.id.ListView01);
	 l1.setAdapter(new EfficientAdapter(this));
	 l1.setTextFilterEnabled(true);
	 displayDate = (TextView) findViewById(R.id.displayDateTextView);
	 currentDate = new Date(year-1900, month-1, day);
		SimpleDateFormat sdf = new SimpleDateFormat("MMM d yyyy");
		displayDate.setText(sdf.format(currentDate));
	 ImageButton prevButton = (ImageButton) findViewById(R.id.previousButton);
	 ImageButton nextButton = (ImageButton) findViewById(R.id.nextButton);
	 if (exerciseList != null) {
		 expListAdapter = new SimpleExpandableListAdapter(
					this,
					createGroupList(),	// groupData describes the first-level entries
					R.layout.child_row,	// Layout for the first-level entries
			//		R.layout.child_row1,
					new String[] { "colorName" },	// Key in the groupData maps to display
					new int[] { R.id.childname },
			//		createChildList1(),	// Data under "colorName" key goes into this TextView
					createChildList(),	
			//		R.layout.child_row1,// childData describes second-level entries
			//		new String[]{"shadeName"},
			//		new int[] { R.id.childname}
					
					R.layout.child_row,	// Layout for second-level entries
					new String[] { "shadeName", "rgb" },	// Keys in childData maps to display
					new int[] { R.id.childname, R.id.rgb }	// Data under the keys above go into these TextViews
				);
	 System.out.println("At ExpanadableList");
		setListAdapter( expListAdapter );
		expListAdapter.notifyDataSetChanged();
	 }
	
	
	 nextButton.setOnClickListener(new OnClickListener() {


			public void onClick(View v) {
				date1 = incrementDate(month,day,year);
				ListView l1 = (ListView) findViewById(R.id.ListView01);
				 l1.setAdapter(new EfficientAdapter(exerciseObj));
				 l1.setTextFilterEnabled(true);
				updateProgressBar(month, day, year);
				simpleExpandable();
               	updateWhatIBurnt();
				currentDate = new Date(year-1900, month-1, day);
				SimpleDateFormat sdf = new SimpleDateFormat(" MMM d yyyy");
				displayDate.setText(sdf.format(currentDate));
				System.out.println("Current Date" + month +year +day);
			}
		});
	 prevButton.setOnClickListener(new OnClickListener() {


			public void onClick(View v) {
//				
				date1 = decrementDate(month,day,year);
				ListView l1 = (ListView) findViewById(R.id.ListView01);
				 l1.setAdapter(new EfficientAdapter(exerciseObj));
				 l1.setTextFilterEnabled(true);
				updateProgressBar(month, day, year);
				simpleExpandable();
		        updateWhatIBurnt();
				currentDate = new Date(year-1900, month-1, day);
				SimpleDateFormat sdf = new SimpleDateFormat("MMM d yyyy");
				displayDate.setText(sdf.format(currentDate));
				System.out.println("Current Date" + month +year +day);
			}
		});
	
	 textViewCal = (TextView) findViewById(R.id.TextView05);
	 adv_cat = (Button)findViewById(R.id.advcat);
   adv_cat.setOnClickListener(new clicker());
   try {
	 db = new DailyInfoDBAdapter1(this);
	// db.open();
	// boolean delete = db.deleteTitle(new Integer(id).toString());
	//db.close();
   } catch (Exception ex){
		 System.out.println("Exception in Custom_ProgressBar");
	 }
	updateProgressBar(month,day,year);
	 
	 
	 
	 }
	 
	 private static final String[] country = { "Morning", "Noon", "Evening",
	 "Night" };
	 private static final String mod = "Mod"
	 ;
	 private static final String light = "Light"
	 ;
	 private static final String vigorous = "Vigorous"
	 ;
	 
	
	 public  void insertIntoDB(int caloriesBurned) {
        String exerciseName = "unknown";
		
         String btnMlightValString, userIdString;
        db.open();        
        long idl;
        Calendar c = Calendar.getInstance();
        
        Date date = convertStringToDate(day, month, year);
        caloriesBurnt = db.getCaloriesBurntForDay(date);
        String categoryName = "dummy";
        btnMlightValString = new Integer(caloriesBurned).toString();
        userIdString = new Integer(id).toString();
        idl = db.insertUserInfo(
        		userIdString,
        		categoryName,
        		exerciseName,
        		"0",
        		btnMlightValString,
        		date); 
        Cursor cc = db.getAllUsers();
        System.out.println("Inside cursor");
        if (cc.moveToFirst()) {       
        	do {          
        		System.out.println("UserId " +cc.getString(0));
                System.out.println("Calories Burned " +cc.getString(5));
                System.out.println("Date"  +cc.getString(6));
            } while (cc.moveToNext());
        }
        else
          System.out.println("No data found");
        db.close();
	 }
	 
	
	 
	
	 class  clicker implements Button.OnClickListener {  
			//	  @Override;
			    	public void onClick(View v) {
			    		
			    		if (v == adv_cat){
			    			Bundle bun = new Bundle();
			    			Intent intent = new Intent();
			    			bun.putInt("monthVal", month);
			    			bun.putInt("dayVal", day);
			    			bun.putInt("yearVal", year);
			    			intent.setClass(Exercise.this, AdvancedExercise.class);
			    			intent.putExtras(bun); 
			    	    	 startActivity(intent);
			    		}
			    			
			    	}
			  }	
	 public static Date convertStringToDate(int date, int month, int year) {
         
         SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
         Date theDate = null;
         String in = date + "/" + month + "/" + year;
         try {
             
             theDate = dateFormat.parse(in); 
             return theDate;
         } catch (ParseException e) {
             e.printStackTrace();
         }
			return theDate;
         
     }
	 
	 public static void updateProgressBar(int month, int day, int year) {
	 int maximumCal = 1000;
	 int caloriesBurned = calBurnt(month,day,year);
	 int calBurnPer = (caloriesBurned * 100)/ maximumCal ;
	 System.out.println("CAlories Burned % " +calBurnPer);
	 pb.setProgress(calBurnPer);
	 String caloriesBurnedText = "CaloriesBurned: ";
	 caloriesBurnedText = new StringBuffer().append(caloriesBurnedText).append(caloriesBurned).toString();
	 textViewCal.setText(caloriesBurnedText);
	 }
	 
	
	public static int calBurnt(int month, int day, int year){
		try {
			 
		     Date date = convertStringToDate(day, month, year);
			 db.open();
			caloriesBurnt = db.getCaloriesBurntForDay(date);
			db.close();
		   } catch (Exception ex){
				 System.out.println("Exception in Custom_ProgressBar");
			 }
		return caloriesBurnt;
		
	}
	private void showExerciseMenuForDate(Date date){
		TextView monthText = (TextView) findViewById(R.id.MonthDisplayTextView);
		SimpleDateFormat sdf = new SimpleDateFormat("DD MMMM yyyy");
		monthText.setText(sdf.format(date));
		DailyInfoDBAdapter1 db = new DailyInfoDBAdapter1(this);
		updateProgressBar(month,day,year);
	}

public ChangeDate incrementDate(int monthV, int dayV, int yearV){
	ChangeDate changeDate = new ChangeDate(monthV , dayV, yearV);
	changeDate = changeDate.next();
	month = changeDate.month ;
	day = changeDate.day;
	year = changeDate.year;
	 System.out.println("Current Date1     " +"  " +changeDate.month +"   "+changeDate.year +"     " +changeDate.day);
	return changeDate;
	
}
public ChangeDate decrementDate(int monthV, int dayV, int yearV){
	ChangeDate changeDate = new ChangeDate(monthV , dayV, yearV);
	changeDate = changeDate.previous();
	month = changeDate.month ;
	day = changeDate.day;
	year = changeDate.year;
	 System.out.println("Decrement Current Date1     " +"  " +changeDate.month +"   "+changeDate.year +"     " +changeDate.day);
	return changeDate;
	
}
private List createGroupList() {
	  ArrayList result = new ArrayList();
	  for( int i = 0 ; i < colors.length ; ++i ) {
			HashMap m = new HashMap();
		    m.put( "colorName",colors[i] );
			result.add( m );
		  }
		  return (List)result;
	   }

private List createChildList() {
	
	ArrayList result = new ArrayList();
	System.out.println("Shades   " +shades1);
	for( int i = 0 ; i < shades1.length ; i++ ) {
	
// Second-level lists
	  ArrayList secList = new ArrayList();
	  for( int n = 0 ; n < shades1[i].length ; n += 1 ) {
	    HashMap child = new HashMap();
		child.put( "shadeName", shades1[i][n] );
//	    child.put( "rgb", shades1[i][n+1] );
	    secList.add( child );
	  }
	  result.add( secList );

	}
	return result;
  }		
public void simpleExpandable(){
	SimpleExpandableListAdapter simpleExpand = null;
	 Date date = convertStringToDate(day, month, year);
	 try {
		
		 db.open();
	//	 boolean delete = db.deleteTitle(new Integer(id).toString());
		 exerciseList = db.getWhatIBurntToday(date);
		 db.close();
	        System.out.println("excercise list" +exerciseList);
	        if (exerciseList == null) {
	        	shades1 = null;
	        }
	        if (exerciseList != null){
	        int len = exerciseList.length;
	        shades1 = new String[1][len];
	        for (int v = 0;v <len; v++){
	        	shades1[0][v] = exerciseList[v];
	        }
	        }
	   } catch (Exception ex){
			 System.out.println("Exception in Custom_ProgressBar");
		 }
	   if (expListAdapter != null)
	   expListAdapter.notifyDataSetChanged();
	   
}

public void updateWhatIBurnt(){
	if (exerciseList != null) {
    try{
        this.expListAdapter =
                new SimpleExpandableListAdapter(
                    this,
                    createGroupList(),    // groupData describes the first-level entries
                    R.layout.child_row,    // Layout for the first-level entries
            //        R.layout.child_row1,
                    new String[] { "colorName" },    // Key in the groupData maps to display
                    new int[] { R.id.childname },
            //        createChildList1(),    // Data under "colorName" key goes into this TextView
                    createChildList(),    
            //        R.layout.child_row1,// childData describes second-level entries
            //        new String[]{"shadeName"},
            //        new int[] { R.id.childname}
                    
                    R.layout.child_row,    // Layout for second-level entries
                    new String[] { "shadeName", "rgb" },    // Keys in childData maps to display
                    new int[] { R.id.childname, R.id.rgb }    // Data under the keys above go into these TextViews
                );
        
        System.out.println("At ExpanadableList");
        expListAdapter.notifyDataSetChanged();
            setListAdapter( expListAdapter );
        
        }catch(Exception ex){
            ex.printStackTrace();
        }
}
	else{
		this.expListAdapter = null;
	}
    
}
}
